package com.lang.downloader.http.header;

import com.lang.exception.ReflectException;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpRequestHeaderKeySet {

    public Set<Map.Entry<String, String>> headers() {
        Map<String, String> headerMap = new HashMap<>();
        Class<? extends HttpRequestHeaderKeySet> type = this.getClass();
        Field[] declaredFields = type.getDeclaredFields();
        if (declaredFields.length > 0) {
            for (Field field : declaredFields) {
                int modifiers = field.getModifiers();
                if (!Modifier.isStatic(modifiers)
                        && !Modifier.isFinal(modifiers)
                        && Modifier.isPrivate(modifiers)
                        && field.isAnnotationPresent(HttpHeader.class)) {
                    HttpHeader httpHeader = field.getAnnotation(HttpHeader.class);
                    String getterName = "get" + StringUtils.capitalize(field.getName());
                    try {
                        Method getterMethod = type.getMethod(getterName);
                        Object value = getterMethod.invoke(this);
                        if (value != null) {
                            headerMap.put(httpHeader.name(), (String) value);
                        }
                    } catch (Exception e) {
                        throw new ReflectException(e);
                    }
                }
            }
        }
        return headerMap.entrySet();
    }

}
